package com.example.service.Impl;

import com.example.common.constant.MessageConstant;
import com.example.common.exception.LoginFailedException;
import com.example.mapper.UserMapper;
import com.example.pojo.dto.UserDTO;
import com.example.pojo.dto.UserLoginDTO;
import com.example.pojo.entity.User;
import com.example.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public boolean addUser(UserDTO userDTO)
    {
        //TODO 添加头像数据
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        user.setCreateTime(LocalDateTime.now());
        //md5加密
        user.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));
        return userMapper.insert(user)>0;
    }

    @Override
    public void login(UserLoginDTO userLoginDTO) {
        User user = userMapper.selectByName(userLoginDTO.getUsername());
        if (user==null)
        {
            throw new LoginFailedException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        String password = DigestUtils.md5DigestAsHex(userLoginDTO.getPassword().getBytes());
        if (!user.getPassword().equals(password))
        {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
    }
}
